package com.waypolice.manager.controller;

import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.constant.CmsResult;
import com.waypolice.common.utils.FastDfsClient;
import com.waypolice.common.utils.MathUtils;
import com.waypolice.manager.service.*;
import com.waypolice.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 *
 * @author zyp
 * @description 我的借阅action
 * @create 2019-03-12 9:52
 */
@Controller
@Api(value = "我的借阅控制器", description = "我的借阅：列表、查看等")
@RequestMapping(value="/pcwindow")
public class BorrowMyAction {

    private static final Logger logger = LoggerFactory.getLogger(BorrowMyAction.class);

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @Autowired
    private BorMyService borrowMyService;

    @Autowired
    protected UserService userService;

    @Autowired
    private VolAndItemService volAndItemService;

    @Autowired
    private CmsSinItemService cmsSinItemService;

    @Autowired
    private CmsBrowseRegisterService cmsBrowseRegisterService;

    @Autowired
    private CmsPrintingRegisterService cmsPrintingRegisterService;

    /**
     * @author:zyp
     * @description 跳转到我的借阅功能
     * @date: 2019/3/13 8:47
     * @return 
     */
    @ApiOperation(value = "我的借阅功能跳转")
    @RequestMapping(value = "/toBorrowMy")
    public String toAccreditList(){
        return "/borrowManager/borrowMy";
    }

    /**
     * @author:zyp
     * @description 获取我借阅的列表
     * @date: 2019/3/21 11:56
     * @return 
     */
    @ApiOperation(value = "获取我借阅的列表")
    @RequestMapping(value = "/getBorrowMy")
    @ResponseBody
    public Object getBorrowMy(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                               @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                               @RequestParam(required = false, defaultValue = "", value = "search") String search){
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        List<UpmsUser> user = userService.findByName(username);
        Map<String,Object> object = borrowMyService.getBorrowMy(offset,limit,search,user.get(0).getUserId());
        return object;
    }

    /**
     * @author:zyp
     * @description 归还线上借阅的授权文件
     * @date: 2019/3/13 9:22
     * @return
     */
    @ApiOperation(value = "归还线上借阅的授权文件")
    @RequestMapping(value = "/returnAccreditArch")
    @ResponseBody
    public Object returnAccreditArch(String ids){
        int count = borrowMyService.returnAccreditArch(ids);
        return new CmsResult(1,"success", count);
    }


    /**
     * @author:zyp
     * @description 查看线上借阅的授权文件
     * @date: 2019/3/22 10:54
     * @return 
     */
    @ApiOperation(value = "查看线上借阅的授权文件")
    @RequestMapping(value = "/watchOriginalImg/{id}/{fileShape}")
    @ResponseBody
    public byte[] watchOriginalImg(@PathVariable("id") Long id,
                                       @PathVariable("fileShape") int fileShape,
                                   HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        String pdfUrl = "";
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        List<UpmsUser> user = userService.findByName(username);
        CmsBrowseRegister cmsBrowseRegister = new CmsBrowseRegister();
        cmsBrowseRegister.setBrowseFileId(id);
        //如果当前的文件形式为卷、件 则 fileShape为1
        switch (fileShape){
            case (int)BorrowConstant.BORROW_FILE_VOLUM:
            case (int)BorrowConstant.BORROW_FILE_ITEM:
                fileShape = 1;
                CmsJudItem cmsJudItem = volAndItemService.selectByItemId(id);
                String itemUrl = cmsJudItem.getItemStr2();
                pdfUrl = itemUrl.replace(IMAGE_SERVER_URL,"");
                break;
            case (int)BorrowConstant.BORROW_FILE_SIN_ITEM:
                fileShape = (int)BorrowConstant.BORROW_FILE_SIN_ITEM;
                CmsSinItem cmsSinItem = cmsSinItemService.selectSinItemById(id);
                String sinUrl = cmsSinItem.getItemStr2();
                pdfUrl = sinUrl.replace(IMAGE_SERVER_URL,"");
                break;
                default:
        }
        cmsBrowseRegister.setBrowseFileShape(fileShape);
        cmsBrowseRegister.setBrowseUserId((long)user.get(0).getUserId());
        cmsBrowseRegisterService.insertSelective(cmsBrowseRegister);

        byte[] bytedownloadFile = new byte[]{};
        try {
            FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
            bytedownloadFile = fastDFSClient.getBytedownloadFile(pdfUrl);
        } catch (Exception e) {
            logger.error("连接fastDFS 失败！！");
        }
        return bytedownloadFile;
    }
    
    /**
     * @author:zyp
     * @description 记录打印情况
     * @date: 2019/4/17 9:22
     * @return 
     */
    @ApiOperation(value = "记录打印情况")
    @RequestMapping(value = "/printRegist")
    @ResponseBody
    public Object printRegist(Long id,int fileShape){
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        List<UpmsUser> user = userService.findByName(username);
        CmsPrintingRegister cmsPrintingRegister = new CmsPrintingRegister();
        cmsPrintingRegister.setPrintingFileId(id);
        int fileType;
        switch (fileShape){
            case (int)BorrowConstant.BORROW_FILE_VOLUM:
            case (int)BorrowConstant.BORROW_FILE_ITEM:
                fileShape = 1;
                CmsJudItem cmsJudItem = volAndItemService.selectByItemId(id);
                CmsJudVolume cmsJudVolume = volAndItemService.selectCmsJudVolumeByVolId(cmsJudItem.getItmeVolId());
                fileType = MathUtils.string2int(cmsJudVolume.getVolClass());
                break;
            case (int)BorrowConstant.BORROW_FILE_SIN_ITEM:
                fileShape = (int)BorrowConstant.BORROW_FILE_SIN_ITEM;
                CmsSinItem cmsSinItem = cmsSinItemService.selectSinItemById(id);
                fileType = MathUtils.string2int(cmsSinItem.getItemExp1());
                break;
            default:
                fileType = 0;
        }
        cmsPrintingRegister.setPrintingFileShape(fileShape);
        cmsPrintingRegister.setPrintingUserId((long)user.get(0).getUserId());
        cmsPrintingRegister.setPrintingFileType(fileType);
        cmsPrintingRegisterService.insertSelective(cmsPrintingRegister);
        return new CmsResult(1,"",null);
    }
}